var currentRecordNum = 0; // 当前页浏览的记录数 包含不符合条件的
var loadJobCount = 0; //加当页面所有的职位数量，（包含符合筛选条件和不符合筛选条件的）
var positionsEligibleForApplication = []; //是dom元素，符合筛选条件可以投递的职位
var deliverMaxNum = 2;
var salary = 25;

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "status") {
    if (message.isRunning) {
      sendResponse({ data: "运行程序" });
      startProgram();
    } else {
      sendResponse({ data: "程序结束运行" });
      cleanSelectView();
    }
    // 在这里添加你想要执行的程序逻辑
  }
});

chrome.storage.onChanged.addListener((changes) => {
  if (changes.runningOneStatus && changes.runningOneStatus.newValue === "done") {
    // 生成一个1000到30000的随机整数
    var random = Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000;
    console.log(" 完成了一个，随机等待：", random);
    var T = setTimeout(() => {
      clearTimeout(T);
      runningOne();
    }, random);
  }
  if (changes.deliverMaxNum && changes.deliverMaxNum.newValue) {
    console.log("改变投递数量");
    deliverMaxNum = Math.floor(changes.deliverMaxNum.newValue);
  }
  if (changes.salary && changes.salary.newValue) {
    console.log("改变薪资");
    salary = Math.floor(changes.salary.newValue);
  }
});

const fixMappedOcrText = (text) => {
  return text.replace(/[\uE031-\uE03A]/g, (char) => {
    const code = char.charCodeAt(0);
    return code >= 0xe031 && code <= 0xe03a ? String(code - 0xe031) : char;
  });
};

async function filterCondition(index) {
  // 所有条件都满足才返回true
  var isFilterCompay = true;
  var ifFilterSalary = false;
  var company = (await chrome.storage.local.get("filterCompany")) || [];
  var bossCompanyName = document.querySelector(".rec-job-list").querySelectorAll(".card-area")[index].querySelector(".boss-name").innerHTML;
  var bossSalaryStr = document.querySelector(".rec-job-list").querySelectorAll(".card-area")[index].querySelector(".job-salary").innerHTML;
  var bossSalaryStrTransform = fixMappedOcrText(bossSalaryStr);
  var bossSalary = bossSalaryStrTransform.match(/-(.*?)K/);
  bossSalary = bossSalary ? bossSalary[1] : 0;
  // console.log(bossCompanyName, "bossCompanyName", bossSalary)
  if (company.filterCompany && company.filterCompany.length !== 0) {
    isFilterCompay = !company.filterCompany.some((item) => {
      return bossCompanyName.includes(item);
    });
  }
  ifFilterSalary = bossSalary >= salary;
  return isFilterCompay && ifFilterSalary;
}

async function pullFetchList() {
  var parentEl = document.querySelector(".job-list-container");
  var allTarget = document.querySelector(".rec-job-list").querySelectorAll(".card-area");
  var len = allTarget.length;
  var lastItem = allTarget[len - 1];
  const parentRect = parentEl.getBoundingClientRect();
  const targetRect = lastItem.getBoundingClientRect();
  const offset = targetRect.top - parentRect.top + parentEl.scrollTop;
  window.scrollTo({
    top: offset,
    behavior: "smooth", // 如果你不需要动画就去掉 behavior
  });
}

async function isEndProcess() {
  var isNext = await chrome.storage.local.get("isRunning");
  return new Promise((resolve) => {
    if (!isNext.isRunning) {
      window.alert(`手动结束，共投递了（${currentRecordNum-1}）份简历`);
      currentRecordNum = 0;
      resolve(true);
    }
    if (currentRecordNum - 1 < deliverMaxNum) {
      resolve(false);
    } else {
      console.log("全部完成");
      window.alert(`全部完成，共投递了（${currentRecordNum-1}）份简历`);
      cleanSelectView();
      currentRecordNum = 0;
      chrome.storage.local.set({
        isRunning: false,
      });
      resolve(true);
    }
  });
}

function cleanSelectView() {
  var allUlTag = document.querySelector(".rec-job-list").querySelectorAll(".card-area");
  allUlTag.forEach((item) => {
    item.querySelector(".job-card-box").style.border = "none";
  });
}

function selectView(dom) {
  cleanSelectView();
  dom.querySelector(".job-card-box").style.border = "2px solid red";

  // dom.style.background = "beige";
  // dom.scrollIntoView({
  //   behavior: "smooth",
  //   block: "center",
  // });
}

function  scrollIntoParentView(parentEl, targetEl) {
  if (!parentEl || !targetEl) return;

  const parentRect = parentEl.getBoundingClientRect();
  const targetRect = targetEl.getBoundingClientRect();

  const offset = targetRect.top - parentRect.top + parentEl.scrollTop;

  window.scrollTo({
    top: offset,
    behavior: "smooth", // 如果你不需要动画就去掉 behavior
  });
}

async function runningOne() {
  currentRecordNum++;
  var isEnd = await isEndProcess();
  if (isEnd) {
    return;
  }
  var container = document.querySelector(".job-list-container");
  var item = positionsEligibleForApplication.shift();
  console.log(positionsEligibleForApplication.length, "positionsEligibleForApplication");
  if (positionsEligibleForApplication.length <= 2) {
    await pullFetchList();
    setTimeout(async () => {
      scrollIntoParentView(container, item);
      await getCanRunTask();
    }, 2000);
  } else {
    scrollIntoParentView(container, item);
  }

  item.click();
  selectView(item);
  chrome.storage.local.set({
    runningOneStatus: "running",
  });
  const chatUrl = item.querySelector(".job-name").href;
  // 打开一个新的标签页
  chrome.runtime.sendMessage({ action: "open_new_tab", url: chatUrl });
}

async function getCanRunTask() {
  var res = [];
  var allTarget = document.querySelector(".rec-job-list").querySelectorAll(".card-area");
  console.log(allTarget, "allTarget");
  var len = allTarget.length;
  for (let i = loadJobCount; i < len; i++) {
    var isPass = await filterCondition(i);
    if (isPass) {
      res.push(allTarget[i]);
    }
  }
  loadJobCount = len;
  positionsEligibleForApplication = [...positionsEligibleForApplication, ...res];
  return res;
}

async function startProgram() {
  // 你的程序逻辑
  console.log("程序逻辑执行中...");
  // 初使化数据
  await getCanRunTask();
  runningOne();
}

window.onload = function () {
  // 其他初始化逻辑
  chrome.storage.local.get("deliverMaxNum", (data) => {
    if (data.deliverMaxNum) {
      deliverMaxNum = data.deliverMaxNum;
    }
  });
  chrome.storage.local.get("salary", (data) => {
    if (data.salary) {
      salary = data.salary;
    }
  });
};
